#include "struct.h"
#define GET_BYTE(vbyte, index) (((vbyte) & (1 << ((index) ^ 7))) != 0)

void unzip(char *filename, HEAD *fileHead, CODING *tree, int headVariety) {
    FILE *fp = fopen(filename,"rb");
    int i;
    char temp[3], ch;
    for( i = 0; i < 3; i++ ) {
        temp[i] = *(fileHead->flag + i);
    }
    char *name = getName(filename);
    strcat(name, "temp.");
    strcat(name, temp);
    FILE *tar = fopen(name, "wb");
    fseek(fp, 0, SEEK_END);
    int index = 0, root = ftell(fp);
    CODING *ptree = tree;
    unsigned char p;
    fseek(fp, (16 + 8*headVariety), SEEK_SET);
    int current = ftell(fp);
    fread(&ch, sizeof(unsigned char), 1, fp);
    while( 1 ) {
        if(ptree->leftChild == NULL && ptree->rightChild == NULL) {
            p = ptree->charFreq.charbody;
            fwrite(&p, sizeof(unsigned char), 1, tar);
            ptree = tree;
        }

        if( current == root && index == fileHead->lastValueBit) {
            break;
        }

        if(GET_BYTE(ch, index)) {
            ptree = ptree->rightChild;
        } else {
            ptree = ptree->leftChild;
        }
        if( ++index >= 8 ) {
            index = 0;
            ch = 0;
            fread(&ch, sizeof(unsigned char), 1, fp);
            current = ftell(fp);
        }
    }

    printf("\n-----------------\nunzip successfully!\n-----------------\n");
    fclose(fp);
    fclose(tar);
}
